package _22_从上往下打印二叉树;

/**
 * 题目描述
 * 从上往下打印出二叉树的每个节点，同层节点从左至右打印。层序遍历
 */

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if(root==null) return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode r = queue.poll();
            list.add(r.val);

            if(r.left!=null) queue.add(r.left);
            if(r.right!=null) queue.add(r.right);

        }
        return list;
    }
    public ArrayList<Integer> PrintFromTopToBottomTest(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode r = queue.poll();
            if(r==null){
                continue;
            }
            list.add(r.val);
            queue.add(r.left);
            queue.add(r.right);
        }
        return list;
    }
}
